package com.wxscrmplus.customer.listener;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.wxscrmplus.common.core.domain.model.LoginUser;
import com.wxscrmplus.common.excel.ExcelListener;
import com.wxscrmplus.common.excel.ExcelResult;
import com.wxscrmplus.common.exception.ServiceException;
import com.wxscrmplus.common.helper.LoginHelper;
import com.wxscrmplus.common.utils.spring.SpringUtils;
import com.wxscrmplus.customer.domain.Contact;
import com.wxscrmplus.customer.domain.Customer;
import com.wxscrmplus.customer.domain.FollowUser;
import com.wxscrmplus.customer.domain.CustomerLog;
import com.wxscrmplus.customer.domain.excel.CustomerImportExcel;
import com.wxscrmplus.customer.domain.vo.CusTypeVo;
import com.wxscrmplus.customer.mapper.*;
import com.wxscrmplus.customer.mapper.*;
import com.wxscrmplus.drainage.domain.vo.DraChannelVo;
import com.wxscrmplus.drainage.mapper.DraChannelMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

/**
 * 导入系统客户
 */
@Slf4j
public class SyncCustomerImportListener extends AnalysisEventListener<CustomerImportExcel> implements ExcelListener<CustomerImportExcel> {

    private final CustomerLogMapper customerLogMapper;
    private final CustomerMapper customerMapper;
    private final ContactMapper contactMapper;
    private final LoginUser loginUser;
    private final DraChannelMapper channelMapper;
    private final FollowUserMapper followUserMapper;
    private final CusTypeMapper cusTypeMapper;
    private int successNum = 0;
    private int failureNum = 0;
    private final StringBuilder successMsg = new StringBuilder();
    private final StringBuilder failureMsg = new StringBuilder();

    public SyncCustomerImportListener() {
        this.customerLogMapper = SpringUtils.getBean(CustomerLogMapper.class);
        this.customerMapper = SpringUtils.getBean(CustomerMapper.class);
        this.channelMapper = SpringUtils.getBean(DraChannelMapper.class);
        this.loginUser = LoginHelper.getLoginUser();
        this.contactMapper = SpringUtils.getBean(ContactMapper.class);
        this.cusTypeMapper = SpringUtils.getBean(CusTypeMapper.class);
        this.followUserMapper = SpringUtils.getBean(FollowUserMapper.class);
    }

    @Transactional
    @Override
    public void invoke(CustomerImportExcel excel, AnalysisContext context) {
        Customer customer = BeanUtil.toBean(excel, Customer.class);
        try {
            if (StrUtil.isBlank(excel.getName())) {
                throw new ServiceException("客户名称不能为空");
            }
            if (StrUtil.isBlank(excel.getGender())) {
                throw new ServiceException("客户性别不能为空");
            }
            if (ObjectUtil.isNotNull(excel.getCusTypeId())) {
                CusTypeVo cusTypeVo = cusTypeMapper.selectVoById(excel.getCusTypeId());
                if (ObjectUtil.isEmpty(cusTypeVo)) {
                    throw new ServiceException("客户类型ID不存在");
                }
            }
            customer.setCreateBy(loginUser.getUsername());
            customer.setEntryType(Customer.EntryTypeFieldEnums.TWO.getValue());
            customer.setOpportunityAmount(BigDecimal.ZERO);
            customer.setMaintainCost(BigDecimal.ZERO);
            customer.setFollowStage(Customer.FollowStageFieldEnums.DAIGOUTONG.getValue());
            customerMapper.insert(customer);
            CustomerLog customerLog = new CustomerLog();
            customerLog.setCustomerId(customer.getCustomerId());
            customerLog.setAbstractText("客户入库");
            customerLogMapper.insert(customerLog);
            Long customerId = customer.getCustomerId();
            //绑定客户跟进人
            FollowUser followUser = new FollowUser();
            followUser.setChannelId(excel.getChannelId());
            followUser.setDelType(FollowUser.DelTypeFieldEnums.ZERO.getValue());
            followUser.setRelType(FollowUser.RelTypeFieldEnums.ONE.getValue());
            followUser.setCreateBy(loginUser.getUsername());
            followUser.setCustomerId(customerId);
            followUser.setUserId(loginUser.getUserId());
            followUser.setWinCost(BigDecimal.ZERO);
            followUser.setFollowStage(Customer.FollowStageFieldEnums.DAIGOUTONG.getValue());
            followUserMapper.insert(followUser);
            Long channelId = excel.getChannelId();
            if (ObjectUtil.isNotEmpty(channelId)) {
                DraChannelVo draChannelVo = channelMapper.selectVoById(channelId);
                if (ObjectUtil.isEmpty(draChannelVo)) {
                    throw new ServiceException("获客渠道ID不存在");
                }
                followUser.setWinCost(draChannelVo.getCost());
            }
            //导入联系方式
            List<Contact> contactList = excel.buildContactWay();
// 9b654d8ffd6a1e56b804df17d0b62b72
            if (CollUtil.isNotEmpty(contactList)) {
                contactList.forEach(contact -> {
                    contact.setCustomerId(customerId);
                    contact.setUserId(loginUser.getUserId());
                    contact.setCreateBy(loginUser.getUsername());
                });
                contactMapper.insertBatch(contactList);
            }
            successNum++;
            successMsg.append("<br/>").append(successNum).append("、客户 ").append(customer.getName()).append(" 导入成功");
        } catch (Exception e) {
            failureNum++;
            String msg = "<br/>" + failureNum + "、客户 " + customer.getName() + " 导入失败：";
            failureMsg.append(msg).append(e.getMessage());
            log.error(msg, e);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }

    @Override
    public ExcelResult<CustomerImportExcel> getExcelResult() {
        return new ExcelResult<CustomerImportExcel>() {

            @Override
            public String getAnalysis() {
                if (failureNum > 0) {
                    failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
                    throw new ServiceException(failureMsg.toString());
                } else {
                    successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
                }
                return successMsg.toString();
            }

            @Override
            public List<CustomerImportExcel> getList() {
                return null;
            }

            @Override
            public List<String> getErrorList() {
                return null;
            }
        };
    }
}
